/**
 * @file TS.h
 *
 * @author Luc Fourestier
 * @date 2009
 */

#ifndef TS_H_
#define TS_H_

#define TS_SIZE 188

// Errors
#define TS_ERROR_NOT_A_TS 	1

// TS transmission param over network
#define MAX_PACKET_PER_MTU 7 // if MTU = 1500
#define MAX_CHUNK_SIZE (MAX_PACKET_PER_MTU*TS_SIZE)

/**
 * @brief A NULL packet
 */
extern unsigned char NullPacket[];

/**
 * The adaptation field
 */
typedef struct TS_AdaptationField_s
{
	unsigned char adaptation_field_length;

	// if (adaptation_field_length > 0)
	unsigned char discontinuity_indicator;
	unsigned char random_access_indicator;
	unsigned char elementary_stream_priority_indicator;
	unsigned char PCR_flag;
	unsigned char OPCR_flag;
	unsigned char splicing_point_flag;
	unsigned char transport_private_data_flag;
	unsigned char adaptation_field_extension_flag;

    // if (PCR_flag = = '1')
	unsigned long long program_clock_reference_base;
	unsigned short program_clock_reference_extension;

    // if (OPCR_flag = = '1')
	unsigned long long original_program_clock_reference_base;
    unsigned short original_program_clock_reference_extension;

    // if (splicing_point_flag = = '1')
    unsigned char splice_countdown;

    // if (transport_private_data_flag = = '1')
    unsigned char transport_private_data_length;
	unsigned char private_data_byte[TS_SIZE-4];

    // if (adaptation_field_extension_flag = = '1')
	unsigned char adaptation_field_extension_length;
	unsigned char ltw_flag;
	unsigned char piecewise_rate_flag;
	unsigned char seamless_splice_flag;

	// if (ltw_flag = = '1')
	unsigned char ltw_valid_flag;
	unsigned short ltw_offset;

	// if (piecewise_rate_flag = = '1')
	unsigned int piecewise_rate;

	// if (seamless_splice_flag = = '1')
	unsigned char splice_type;
	unsigned char DTS_next_AU_32_30;
	unsigned char marker_bit_1;
	unsigned short DTS_next_AU_29_15;
	unsigned char marker_bit_2;
	unsigned short DTS_next_AU_14_0;
	unsigned char marker_bit_3;

} TS_AdaptationField_t;

/**
 * The TS packet
 */
typedef struct TS_s
{
	unsigned char sync_byte;
	unsigned char transport_error_indicator;
	unsigned char payload_unit_start_indicator;
	unsigned char transport_priority;
	unsigned short PID;
	unsigned char transport_scrambling_control;
	unsigned char adaptation_field_control;
	unsigned char continuity_counter;

	TS_AdaptationField_t adaptation_field; // if no adaptation_field, adaptation_field_length == 0

	unsigned char data_byte[TS_SIZE-4];
	unsigned int DataByteLength;
} TS_t;

/**
 * @brief Fill the TS
 */
int TS_Create(unsigned char * Buffer, unsigned int *Size, TS_t * TS);

#endif /* TS_H_ */
